<template>
  <el-dialog title="任务列表" :visible="localDialogTableVisible" width="70%" @open="startPolling" @close="onClose">
    <el-table :data="taskList" height="548" :row-style="rowStyle">
      <el-table-column property="name" label="任务名称" ></el-table-column>
      <el-table-column property="fileName" label="文件名称" ></el-table-column>
      <el-table-column property="fileSuffix" label="文件类型"></el-table-column>
      <el-table-column property="status" :formatter="statusFormatter" label="任务状态"></el-table-column>
      <el-table-column property="progress" label="进度"></el-table-column>
      <el-table-column property="gmtCreate" label="创建时间"></el-table-column>
      <el-table-column property="gmtModified" label="更新时间"></el-table-column>
      <el-table-column label="操作" width="130" align="center">
        <template v-slot="scope">
          <el-button type="text" style="color: var(--orangeRed)" @click="handleDownload(scope.row)">
            下载
          </el-button>
          <el-button type="text" style="color: var(--orangeRed)" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 10px;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchInfo.page"
      :page-size="searchInfo.pageSize"
      layout="total, prev, pager, next, jumper"
      :total="searchInfo.total">
    </el-pagination>
  </el-dialog>
</template>

<script>
import { saveAs } from 'file-saver';
import axios from "axios";
export default {
  props: {
    taskType: {
      type: String,
      default: ''
    }
  },
  watch:{
    taskType(newVal){
      this.searchInfo.type = newVal;
    }
  },
  created() {
  },
  data() {
    return {
      localDialogTableVisible: false,
      taskList: [],
      searchInfo:{
        page: 1,
        pageSize: 5,
        total: 0,
        type: this.taskType
      },
      timer: null,
      statusMap: {
        '-1': '新建',
        '0': '进行中',
        '1': '完成',
        '2': '失败'
      }
    };
  },
  methods:{
    rowStyle(row, rowIndex) {
        // 设置行高为 50px
        return { height: '100px' }
    },
    statusFormatter(row, column, cellValue) {
      return this.statusMap[cellValue];
    },
    handleSizeChange(pageSize) {
      this.searchInfo.pageSize = pageSize
      this.initAllTaskByType()
    },
    handleCurrentChange(page) {
      this.searchInfo.page = page
      this.initAllTaskByType()
    },
    handleDownload(row){
      this.$http.download(this.$constant.baseURL + `/offline-export/download-task/${row.id}`, {}, true)
        .then((res) => {
          // 判断是响应的json还是数据流
          const contentType = res.headers['content-type'];
          if(contentType.includes('application/json')){
            
            new Response(res.data).text().then(text => {
              const data = JSON.parse(text);
              this.$message({
                message: data.msg,
                type: "error"
              });
              return
            })
            
            this.$message({
              message: res.data.msg,
              type: "error"
            });
            return
          }

          // 创建一个新的Blob对象
          const blob = new Blob([res.data]);

          // 获取文件名
          const contentDisposition = res.headers['content-disposition'];
          if(!contentDisposition || !contentDisposition.includes('=')){
            this.$message({
              message: "文件名信息异常！",
              type: "error"
            });
            return
          }

          // 解析文件名
          const encodedFilename = contentDisposition.split('=')[1];
          const decodedFilename = decodeURIComponent(encodedFilename);

          // 使用FileSaver.js保存文件
          saveAs(blob, decodedFilename);
        })
        .catch((error) => {
          console.log(error)
        });
    },
    handleDelete(rowId){
      this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success',
          center: true
        }).then(() => {
          const config = this.$http.getConfig(true)
          axios
            .delete(this.$constant.baseURL + `/offline-export/delete-task/${rowId}`, config.headers)
            .then(() => {
              this.$message({
                message: "删除成功！",
                type: "success"
              });

              this.initAllTaskByType()
            })
            .catch(err => {
              this.$message({
                message: err.message,
                type: "error"
              });
            });
        })
    },
    initAllTaskByType(){
      this.searchInfo.type = this.taskType +'-export'
      this.$http.post(this.$constant.baseURL + `/offline-export/list-task/${this.searchInfo.page}/${this.searchInfo.pageSize}`, this.searchInfo, true)
        .then((res) => {
          this.taskList = res.data.list
          this.searchInfo.total = res.data.total
        })
        .catch((error) => {
          console.log(error)
        });
    },
    startPolling() {
      // 立即调用一次
      this.initAllTaskByType();
      // 设置定时器，定时轮询
      this.timer = setInterval(() => {
        this.initAllTaskByType();
      }, 5000); // 例如每5秒调用一次
    },
    stopPolling() {
      // 清除定时器
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    onClose(){
      this.localDialogTableVisible = false;
      this.stopPolling()
    },
    doOpen(){
      this.localDialogTableVisible = true;
    }
  }
};
</script>

<style scoped>
/* scoped样式 */
.custom-height .el-dialog__body {
  height: 50vh; /* 设置为视口高度的50% */
  overflow-y: auto; /* 如果内容超过高度，只在y轴显示滚动条 */
}
</style>
